/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package com.inspur.edp.metadata.rtcustomization.core;

import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.metadata.rtcustomization.api.entity.ConfigData;
import com.inspur.edp.metadata.rtcustomization.api.entity.MimicTypeEnum;
import com.inspur.edp.metadata.rtcustomization.spi.ConfigDataSaveSpi;
import com.inspur.edp.metadata.rtcustomization.spi.MetadataSaveSpi;
import java.util.List;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 复制保存服务
 */
@Slf4j
public class MimicSaveServiceImpl implements MimicSaveService {

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void mimicSave(MimicTypeEnum mimicTypeEnum, List<GspMetadata> gspMetadataList,
        List<ConfigData> configDataList) {
        metadataSave(mimicTypeEnum, gspMetadataList);
        configDataSave(mimicTypeEnum, configDataList);
    }

    /**
     * 保存元数据
     *
     * @return
     */
    private void metadataSave(MimicTypeEnum mimicTypeEnum, List<GspMetadata> gspMetadataList) {
        if (CollectionUtils.isEmpty(gspMetadataList)) {
            return;
        }
        List<MetadataSaveSpi> metadataSaveSpiList = MimicSpiServiceFactory.getSpiService(mimicTypeEnum, MetadataSaveSpi.class);
        for (MetadataSaveSpi metadataSaveSpi : metadataSaveSpiList) {
            metadataSaveSpi.save(gspMetadataList);
        }
    }

    /**
     * 保存配置
     *
     * @return
     */
    private void configDataSave(MimicTypeEnum mimicTypeEnum, List<ConfigData> configDataList) {
        if (CollectionUtils.isEmpty(configDataList)) {
            return;
        }
        List<ConfigDataSaveSpi> configDataSaveSpiList = MimicSpiServiceFactory.getSpiService(mimicTypeEnum, ConfigDataSaveSpi.class);
        for (ConfigData configData : configDataList) {
            for (ConfigDataSaveSpi configDataSaveSpi : configDataSaveSpiList) {
                configDataSaveSpi.save(configData);
            }
        }
    }
}
